package com.wframe.project.former.web.information;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;

import com.frame.common.SystemConfig;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.pageform.DataPageForm;
import com.frame.pageform.RequestContext;
import com.frame.util.DateConvert;
import com.wframe.project.former.dataservices.information.InformationService;
import com.wframe.project.former.dataservices.information.SmsPushService;

/**
 * 
 * 功能:信息/资讯/广告管理<br>
 * 参数:<br>
 * 作者:王海锋<br>
 * 时间:2017-1-13上午10:59:24<br>
 */
public class InformationPage extends DataPageForm{

	private JdataBean bean;
	private InformationService infoservice=InformationService.getIntance();
	
	/**
	 * 文章列表
	 */
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		setPagination(infoservice.queryInfolList(bean, getPageSize_(), getPageNum()));
		return "/webadmin/information/infoList.jsp";
	}
	
	/**
	 * 
	 * 功能:广告列表<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-3下午11:38:24<br>
	 */
	public String adList() throws Exception {
		// TODO Auto-generated method stub
		setPagination(infoservice.queryInfolList(bean, getPageSize_(), getPageNum()));
		return "/webadmin/advertisement/infoList.jsp";
	}
	
	/**
	 * 
	 * 功能:加载栏目列表<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-12-7下午12:18:01<br>
	 * @throws Exception 
	 */
	public String loadChannel() throws Exception{
		if(bean==null)bean=new JdataBean();
		String pid="";
		if(StringUtils.isNotBlank(bean.getString("code"))){
			JdataBean pbean=infoservice.getChannelByCode(bean.getString("code"));
			pid=pbean.getString("id");
		}
		List<JdataBean> list=infoservice.loadChannel(bean.getString("code"));
		for(JdataBean data:list){
			if(data.getString("pid").equals(pid))data.put("_parentid", 0);
		}
		getJsonObject().put("total",list.size());
    	getJsonObject().put("rows", list);
    	return getJsonObject().toString().replaceAll("_parentid", "_parentId");
	}
	
	/**
	 * 
	 * 功能:加载栏目树<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-12-7下午12:18:01<br>
	 * @throws Exception 
	 */
	public String loadChannelTree() throws Exception{
		if(bean==null)bean=new JdataBean();
		StringBuffer sb=new StringBuffer();
		sb.append("[");
		List<JdataBean> clist=infoservice.querySubChannel(bean.getString("code"));
		for(int i=0;i<clist.size();i++){
			JdataBean c=clist.get(i);
	        if(i!=0)sb.append(",");
	        sb.append("{\"id\":\""+c.getString("code")+"\",\"text\":\""+c.getString("name")+"\",\"state\":\"open\"");
	        //查询子栏目
	        List<JdataBean> sublist=infoservice.querySubChannel(c.getString("code"));
			sb.append(",\"children\":[");
	        for(int s=0;s<sublist.size();s++){
	        	if(s!=0)sb.append(",");
		        sb.append("{\"id\":\""+sublist.get(s).getString("code")+"\",\"text\":\""+sublist.get(s).getString("name")+"\"}");
		    }
	        sb.append("]}");
		}
		sb.append("]");
		return getJsonObject().JSONDATA+sb.toString();
	}
	
	public String showChannelEditA() throws Exception{
		if(StringUtils.isNotBlank(bean.getString("id"))){
			bean=infoservice.getChannel(bean.getString("id"));
		}
    	return "/webadmin/channel/channelEdit1.jsp";
	}
	/**
	 * 
	 * 功能:保存专题栏目<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-3下午11:38:49<br>
	 */
	public String saveChannelA() throws Exception{
		String id=infoservice.saveChannel(getBean());
		getJsonObject().put("id", id);
		getJsonObject().put("code", bean.getString("code"));
		getJsonObject().put("state", "ok");
		return getJsonObject().toString();
	}
	
	public String showChannelEditB() throws Exception{
		if(StringUtils.isNotBlank(bean.getString("id"))){
			bean=infoservice.getChannel(bean.getString("id"));
		}
    	return "/webadmin/channel/channelEdit2.jsp";
	}
	/**
	 * 
	 * 功能:保存专题栏目子栏目<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-3下午11:39:05<br>
	 */
	public String saveChannelB() throws Exception{
		String products=bean.getString("products");
		bean.remove("products");
		String id=infoservice.saveChannel(getBean());
		infoservice.saveChannelProduct(bean.getString("code"),products);
		getJsonObject().put("id", id);
		getJsonObject().put("code", bean.getString("code"));
		getJsonObject().put("state", "ok");
		return getJsonObject().toString();
	}
	
	public String delChannel() throws Exception{
		infoservice.delChannel(bean.getString("id"));
		getJsonObject().put("state", "ok");
		return getJsonObject().toString();
	}
	/**
	 * 加载栏目商品
	 * @return
	 * @throws Exception
	 */
	public String loadChannelProducts() throws Exception{
		if(bean==null)bean=new JdataBean();
		if(StringUtils.isNotBlank(bean.getString("channelid"))){
			JdataBean channel=infoservice.getChannel(bean.getString("channelid"));
			bean.put("code", channel.getString("code"));
		}else bean.put("code","null");
		int pageno=1;
		int size=20;
		if(StringUtils.isNotBlank(getRequest().getParameter("page")))pageno=new Integer(getRequest().getParameter("page"));
		if(StringUtils.isNotBlank(getRequest().getParameter("rows")))size=new Integer(getRequest().getParameter("rows"));
		PageResult pr=infoservice.queryChannelProduct(bean, size,pageno);
		getJsonObject().put("total",pr.getResultCount());
    	getJsonObject().put("rows", pr.getList());
    	return getJsonObject().toString();
	}
	
	/**
	 * 编辑文章信息
	 */
	@Override
	public String show() throws Exception {
		if(bean!=null && StringUtils.isNotBlank(bean.getString("id"))){
			bean=infoservice.getInfo(bean.getString("id"));
			JdataBean content=infoservice.getContent(bean.getString("id"));
			if(content!=null)bean.put("content", content.getString("content"));
		}
		return "/webadmin/information/infoEdit.jsp";
	}
	
	/**
	 * 
	 * 功能:编辑广告信息<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-3下午11:39:59<br>
	 */
	public String adshow() throws Exception {
		List<JdataBean> subchannels=null;
		if(bean!=null && StringUtils.isNotBlank(bean.getString("id"))){
			bean=infoservice.getInfo(bean.getString("id"));
			JdataBean content=infoservice.getContent(bean.getString("id"));
			if(content!=null)bean.put("content", content.getString("content"));
		}else{
			if(bean==null)bean=new JdataBean();
			bean.put("ISSUETIME", DateConvert.toString(new Date(), "yyyy-MM-dd"));
		}
		subchannels=infoservice.querySubChannel(bean.getString("code"));
		getRequest().setAttribute("subchannels", subchannels);
		return "/webadmin/advertisement/infoEdit.jsp";
	}

	@Override
	public String toDel() throws Exception {
		if(getPrimaryKey_()!=null){
			for(String id:getPrimaryKey_()){
				infoservice.delInfo(id);
			}
			getJsonObject().put("state", "delok");
		}
		return getJsonObject().toString();
	}

	/**
	 * 保存文章信息、广告信息
	 */
	@Override
	public boolean toUpdate() throws Exception {
		// TODO Auto-generated method stub
		if(!"3".equals(bean.getString("type")))bean.put("content",null);
		infoservice.saveInfo(bean);
		getJsonObject().put("state", "ok");
		return false;
	}
	
	public String upload() throws Exception{
		JdataBean json=new JdataBean();
		if(RequestContext.getContext().getFileItemList()!=null){
			FileItem fileitem=RequestContext.getContext().getFileItemList().get(0);
			String fname=fileitem.getName();
			int n=fname.lastIndexOf(".");
            String type=fname.substring(n+1);
            String path="/uploadfile/info/files";
            File dirfile=new File(SystemConfig.getInstance().getRootPath()+path);
			if(!dirfile.exists())dirfile.mkdirs();
			Random rd=new Random();
			String newname=DateConvert.toString(new Date(),"yyMMddHHmmssSSS")+rd.nextInt(99)+"."+type;
			String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+getRequest().getContextPath();
	        try {
				fileitem.write(new File(SystemConfig.getInstance().getRootPath()+path+"/"+newname));
				json.put("error", 0);
				json.put("url", basePath+path+"/"+newname);
			} catch (Exception e) {
				e.printStackTrace();
				json.put("error", 1);
				json.put("url", "");
			}
		}
		getResponse().setContentType("text/html; charset=UTF-8");
		getResponse().getWriter().print(getJsonObject().objToJson(json));
		return null;
	}
	/**
	 * 站内消息
	 * @return
	 * @throws Exception
	 */
	public String stationnews() throws Exception{
		setPagination(infoservice.queryStationnews(getPageSize_(), getPageNum()));
		return "/webadmin/information/stationnews.jsp";
	}
	public String stationnewsShow() throws Exception{
		if(bean!=null && StringUtils.isNotBlank(bean.getString("id")))
			bean=infoservice.getStationnews(bean.getString("id"));
		return "/webadmin/information/stationnewsEdit.jsp";
	}
	public String stationnewsSave() throws Exception{
		infoservice.addStationnews(bean);
		getJsonObject().getJsonPage().showOkMsg("添加成功");
		getJsonObject().getJsonPage().closeWin("ok");
		return getJsonObject().toString();
	}
	public String stationnewsDel() throws HibernateException, Exception{
		infoservice.delStationnews(bean.getString("id"));
		return getJsonObject().toString();
	}
	
	public String smsinfos() throws Exception{
		setPagination(infoservice.querySmsinfo(getPageSize_(), getPageNum()));
		return "/webadmin/information/smsinfos.jsp";
	}
	public String smsinfoShow() throws Exception{
		if(bean!=null && StringUtils.isNotBlank(bean.getString("id")))
			bean=infoservice.getSmsinfo(bean.getString("id"));
		return "/webadmin/information/smsinfoEdit.jsp";
	}
	public String smsinfoSave() throws Exception{
		infoservice.addSmsinfo(bean);
		SmsPushService.getIntance().addSmsPush(bean.getString("grade"), bean.getString("content"));
		getJsonObject().getJsonPage().showOkMsg("添加成功");
		getJsonObject().getJsonPage().closeWin("ok");
		return getJsonObject().toString();
	}
	public String smsinfoDel() throws HibernateException, Exception{
		infoservice.delSmsinfo(bean.getString("id"));
		return getJsonObject().toString();
	}

	public JdataBean getBean() {
		return bean;
	}

	public void setBean(JdataBean bean) {
		this.bean = bean;
	}

}
